package com.zm.demo.core.leetcode;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2020/1/7 10:06
 */
public class NumberReverse {

    int reverse(int x) {

        String s = String.valueOf(Math.abs(x));
        StringBuilder sb = new StringBuilder(s);
        s = sb.reverse().toString();

        if ( x > 0){
            int max = (1 << 31)-1;
            String maxStr = Integer.toString(max);
            if (s.length() > maxStr.length()){
                return 0;
            }
            if (s.length() < maxStr.length()){
                return Integer.valueOf(s);
            }
            if (s.length() == maxStr.length()){
                for (int i = 0; i < s.length() ; i++) {
                    if (s.charAt(i) > maxStr.charAt(i)){
                        return 0;
                    }else if (s.charAt(i) < maxStr.charAt(i)){
                        return Integer.valueOf(s);
                    }
                }
                return Integer.valueOf(s);
            }
        } else if (x < 0) {
            int min = (1 << 31);
            String maxStr = Integer.toString(min).replace("-", "");
            int length = maxStr.length();
            if (s.length() > length){
                return 0;
            }
            if (s.length() < length){
                return 0 - Integer.valueOf(s);
            }
            if (s.length() == length){
                for (int i = 0; i < s.length() ; i++) {
                    if (s.charAt(i) > maxStr.charAt(i)){
                        return 0;
                    }else if (s.charAt(i) < maxStr.charAt(i)){
                        return Integer.valueOf("-" + s);
                    }
                }
                return Integer.valueOf("-" + s);
            }
        } else{
            return 0;
        }
        return 0;
    }

    public static void main(String []args){
        Long start = System.currentTimeMillis();
        out.println(new NumberReverse().reverse(-2147483411));
        out.println(System.currentTimeMillis() - start);
    }
}
